class ConfigGenerator {
    apply(compiler) {
        compiler.hooks.thisCompilation.tap('ConfigGenerator', compilation => {
            compilation.hooks.processAssets.tap(
                {
                    name: 'ConfigGenerator',
                    stage: compilation.PROCESS_ASSETS_STAGE_ADDITIONS
                },
                assets => {
                    const asset = assets['config.js']
                    if (!asset) {
                        return
                    }

                    const { RawSource } = compiler.webpack.sources

                    const baseUrl = process.env.PUBLIC_API_BASE_URL
                    const loginUrl = process.env.PUBLIC_LOGIN_URL
                    const wsUrl = process.env.PUBLIC_WS_URL
                    const isEncryption = process.env.PUBLIC_ENCRYPTION
                    const fileUrl = process.env.PUBLIC_FILE_URL

                    const oldContent = asset.source().toString()
                    const updatedContent = oldContent
                        .replace('$url', baseUrl)
                        .replace('$wsUrl', wsUrl)
                        .replace('$loginUrl', loginUrl)
                        .replace('$isEncryption', isEncryption)
                        .replace('$fileUrl', fileUrl)
                    const source = new RawSource(updatedContent)

                    compilation.updateAsset('config.js', source)
                }
            )
        })
    }
}

module.exports = ConfigGenerator
